import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, Alert, RefreshControl
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';
import { RangTime } from '../../../component/common/RangTime.js';
import MethodUtil from '../../../utils/MethodUtil';
import Dictionary from '../../../utils/dictionary';
import { ScrollView, TabRouter } from 'react-navigation';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import moment from 'moment';
import Permission from '../../../utils/permission';
const scale = GLOBAL.SCALE;
const showIcon = require('../../../imgs/global/eye1.png');
const hideIcon = require('../../../imgs/global/eye0.png');
const uriImg = require('../../../imgs/sanjiao3.png');
export class clientFundsDetail extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    let { selectAccount, choice, options } = navigation.state.params
    return {
      headerTitle: '资金账户',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (options <= 1 ?
        <Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} /> :
        <View style={{ marginRight: 10 * scale }}>
          <NewAccount fn={(val) => {
            selectAccount && selectAccount()
          }}
            accountStyles={{ paddingTop: 8 * scale, paddingRight: 0 * scale }}
            imgUrl={require('../../../imgs/downAccount2.png')}
            imgStyle={{
              width: 12 * scale,
              height: 12 * scale,
            }}
            choice={choice ? choice.corpName : ''} />
        </View>
      ),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props);
    let { options, choice, companyIndex, companyId, companyName, isForeign } = props.navigation.state.params || {};
    this.state = {
      status: 'data',
      companyIndex: companyIndex || 0,
      listData: [], // 列表数据
      alertShow: false,
      options: options,
      choice: choice,
      type: '2',
      hideNumber: true,
      Unfold: false,
      data: {},
      isModal: false,
      typesIndex: 0,
      companyName: companyName,
      totalExpend: 0,
      totalInCome: 0,
      isForeign: isForeign,
      canLoadMore: true,
      typeData: [],
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.refresh = true;
    this.totalPage = 1; // 总页数
    this.pageParams = {
      companyId: companyId,
      corpType: '2',
    },
      this.companyId = companyId,
      this.salesData = [],
      this.purchaseData = [],
      this.dateObj = {
        companyId: companyId,
        pageNo: 1,
        pageSize: 10,
        corpType: '2',
        beginTime: moment(moment().subtract(1, 'months').calendar()).format('YYYY-MM-DD') || null,
        endTime: moment().format('YYYY-MM-DD') || null
      }
  }

  async componentWillMount() {
    let { companyIndex } = this.props.navigation.state.params || {};
    let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
      console.log(userInfo.corpInfoTOs)
      this.setState({
        options: userInfo.corpInfoTOs || [],
        choice: companyIndex ? userInfo.corpInfoTOs[companyIndex] : userInfo.corpInfoTOs[0]
      })
      this.props.navigation.setParams({
        options: userInfo.corpInfoTOs || [],
        choice: companyIndex ? userInfo.corpInfoTOs[companyIndex] : userInfo.corpInfoTOs[0]
      });
    }
    await this.getType();
    await this.initPage();
    await this.initDate();

  }
  componentDidMount() {
    this.props.navigation.setParams({
      selectAccount: this._selectAccount
    });
  }

  _selectAccount = async () => {
    this.setState({
      alertShow: !this.state.alertShow
    })
  }
  async _refresh() {
    this.reload = true;
    this.refresh = true;
    this.dateObj.bizType = '';
    this.dateObj.beginTime = moment(moment().subtract(1, 'months').calendar()).format('YYYY-MM-DD') || null;
    this.dateObj.endTime = moment().format('YYYY-MM-DD') || null
    this.setState({
      listData: [],
      typesIndex: 0
    })
    await this.getType();
    await this.initPage();
    await this.initDate();
  }
  async getType() {
    if (this.purchaseData.length == 0) {
      this.purchaseData = await Dictionary.get("FIN_CAPITAL_FREE_TYPE_PURCHASE");
      if (this.purchaseData[0].dictKey) {
        this.purchaseData.unshift({
          dictName: '全部类型',
          dictKey: ''
        })
      }
    }
    if (this.salesData.length == 0) {
      this.salesData = await Dictionary.get("FIN_CAPITAL_FREE_TYPE_SALES");
      if (this.salesData[0].dictKey) {
        this.salesData.unshift({
          dictName: '全部类型',
          dictKey: ''
        })
      }
    }
    if (this.state.type === '2') {
      this.setState({
        typeData: this.salesData
      })
    }
    else {
      this.setState({
        typeData: this.purchaseData
      })
    }
  }
  async initPage() {
    let { corpId } = this.state.options[this.state.companyIndex] || {};
    this.pageParams.corpId = corpId || '';
    this.dateObj.corpId = corpId || '';
    this.dateObj.pageNo = 1;
    let res = await HTTP.POST(API_GENERATE(API.COMPANY_INFO), this.pageParams);
    if (res) {
      this.refresh = false
      this.setState({
        data: res
      })
    }
  }
  async initDate() {
    this.setState({
      status: this.reload ? 'loading' : 'data',
    })
    console.log(this.dateObj.pageNo)
    let data = await HTTP.POST(API_GENERATE(API.COMPANY_TRANS_INFO), this.dateObj);
    if (data) {
      totalInCome = data.totalInCome
      totalExpend = data.totalExpend
      res = data.paginationModel
      this.totalPage = res.totalPage;
      this.reload = false
      this.setState({
        status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
        listData: this.dateObj.pageNo == 1 ? res.rows : this.state.listData.concat(res.rows),
        totalExpend,
        totalInCome
      }, () => {
        this.canLoadMore = true
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }
  togglePassword = () => {
    this.setState({
      hideNumber: !this.state.hideNumber
    })
  }

  _toMoney(num) {
    if (num) {
      num = MethodUtil.toThousands(num || 0, 2)
      return num
    }
    else {
      return 0
    }
  }

  //打开时间弹框
  _timeOpen = () => {
    this.setState({
      showTimeModal: true
    })
  }

  // 选择时间
  _resultCall = (resultData) => {
    this.dateObj.beginTime = resultData.startTime || '';
    this.dateObj.endTime = resultData.endTime;
    this.setState({ showTimeModal: false, }, () => {
      this.reloadPage();
    })
  }
  //切换功能
  _toggle = (onoff) => {
    this.setState({
      isModal: onoff
    })
  }

  //选择状态 回掉函数
  _stateCallBack = (index) => {
    this.dateObj.bizType = this.state.typeData[index].dictKey
    this.setState({
      isModal: false,
      typesIndex: index,
      listData: []
    }, () => {
      this.reloadPage();
    })
  }

  loadMore() {
    if (this.totalPage > this.dateObj.pageNo && !this.reload) {
      this.dateObj.pageNo++;
      this.initDate();
    }
  }
  // 刷新页面
  reloadPage = () => {
    this.dateObj.pageNo = 1;
    this.initDate();
  }
  changeType = (type) => {
    this.setState({
      type,
    }, () => {
      this.dateObj.corpType = type
      this.pageParams.corpType = type
      this._refresh()
    })
  }

  _contentViewScroll = (e) => {
    var offsetY = e.nativeEvent.contentOffset.y; // 已经滚动的距离
    var oriageScrollHeight = e.nativeEvent.layoutMeasurement.height; // 可滚动的可见区域高度
    var contentSizeHeight = Math.round(e.nativeEvent.contentSize.height); // 可滚动的总高度
    if (Math.round(offsetY + oriageScrollHeight) >= contentSizeHeight) {
      if (this.canLoadMore) {
        this.loadMore()
        this.canLoadMore = false
      }
    }
  }


  // 列表
  _renderListItem = () => {
    let { type, listData, isForeign } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: '#fff', paddingHorizontal: 16 * scale }}>
        {listData.map((item, index) => {
          return (
            <TouchableOpacity activeOpacity={1} key={index} onPress={() => {
              this.props.navigation.navigate('myAccount', {
                data: item,
                orderType: type === '2' ? 'S' : 'P',
                corpId: this.pageParams.corpId,
                isForeign
              })
            }} style={[styles.listItem, index == this.state.listData.length - 1 ? { borderBottomWidth: 0 * scale } : null]}>
              <View>
                <Text style={{ marginBottom: 4 * scale, color: "#000" }}>{item.bizTypeName}
                  {(item.bizType === 'FIN_ALLOTMENT_IN' || item.bizType === 'FIN_ALLOTMENT_OUT') && item.orderId ?
                    '-' + item.orderId : null
                  }
                </Text>
                <Text style={styles.listItemTime}>{item.operateTime}</Text>
              </View>
              <View>
                <Text style={[styles.listItemNum, item.operateAmount > 0 ? { color: '#CA0202', } : { color: '#19977B' }]}>{item.operateAmount > 0 ? '+' : ''}{this._toMoney(item.operateAmount)}</Text>
              </View>
            </TouchableOpacity>
          )
        })
        }
      </View>


    )
  }

  render() {
    let { status, data, options, alertShow, companyIndex, type, hideNumber, Unfold, showTimeModal, isModal, typesIndex, listData, companyName, totalExpend, totalInCome, isForeign, typeData } = this.state;
    let { canUserAmt, orderOccupyAmt, depositOccupyAmt, waitClaimAmt, bizStaffClaimAmt, waitConfirmAmt } = data
    return (
      <ScrollView style={styles.container}
        stickyHeaderIndices={[2]}
        onScroll={this._contentViewScroll}
        refreshControl={
          <RefreshControl refreshing={this.refresh} onRefresh={() => { this._refresh() }} />
        }
      >
        <View style={styles.headBox}>
          <View style={styles.flexRow}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <Text style={styles.topText}>
                {type === '2' ?
                  '客户可用余额（元）' : '供应商预收款（元）'
                }
              </Text>
              <TouchableOpacity activeOpacity={1} style={styles.secureEntryBox} onPress={() => { this.togglePassword() }} >
                <Image source={hideNumber ? showIcon : hideIcon} style={styles.secureEntry} />
              </TouchableOpacity>
            </View>
            <View style={styles.flexRow}>
              <TouchableOpacity onPress={() => { this.changeType('2') }} style={[type === '2' ? styles.onClick : styles.unClick, { marginRight: 20 * scale }]}>
                <Text style={type === '2' ? styles.onClickText : styles.topText}>客户</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => { this.changeType('1') }} style={type === '1' ? styles.onClick : styles.unClick}>
                <Text style={type === '1' ? styles.onClickText : styles.topText}>供应商</Text>
              </TouchableOpacity>
            </View>
          </View>
          <View>
            <Text style={styles.topNum}>
              {isForeign !== 1 ? '￥' : '$'} {hideNumber ? this._toMoney(canUserAmt) : '****'}
            </Text>
          </View>
          <View style={{ flexDirection: 'row' }}>
            <TouchableOpacity style={{ width: "60%" }} onPress={() => {
              this.props.navigation.navigate('orderOccupiedList', {
                orderType: type === '2' ? 'S' : 'P',
                corpType: type,
                companyId: this.companyId,
                corpId: this.pageParams.corpId,
                isForeign
              })
            }}>
              <Text style={styles.topText}>
                订单已占用（元）
                </Text>
              <View style={[styles.flexRow, { alignItems: 'center', marginTop: 10 * scale }]}>
                <Text style={styles.MiddleNum}>
                  {isForeign !== 1 ? '￥' : '$'}{hideNumber ? this._toMoney(orderOccupyAmt) : '****'}
                </Text>
                <View style={[styles.flexRow]}>
                  <Text style={styles.detailText}>详情</Text>
                  <Image source={require('../../../imgs/arrow-left.png')} style={[styles.detailImg, { tintColor: '#fff', }]} />
                </View>
              </View>
            </TouchableOpacity>
            {type === '2' ?
              <View>
                <Text style={[styles.topText, { marginLeft: 24 * scale }]}>
                  保证金占用（元）
                  </Text>
                <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 * scale }}>
                  <Text style={styles.middleLine}>|</Text>
                  <Text style={styles.MiddleNum}>
                    {isForeign !== 1 ? '￥' : '$'}{hideNumber ? this._toMoney(depositOccupyAmt) : '****'}
                  </Text>
                </View>
              </View>
              : null
            }
          </View>
        </View>
        <View style={styles.middleBox}>
          <View style={[styles.flexRow, { alignItems: 'center' }]}>
            <Text style={{ fontWeight: '600', fontSize: 14 * scale, color: '#000' }}>{companyName}</Text>
            <TouchableOpacity onPress={() => {
              this.props.navigation.navigate('fundsMail', {
                companyId: this.companyId,
                corpType: type,
                companyName,
                corpId: this.pageParams.corpId,
                isForeign
              })
            }}>
              <Text style={{ fontSize: 12 * scale, color: '#0E5BC6' }}>邮件推送账单</Text>
            </TouchableOpacity>
          </View>
          {type === '2' ?
            <View>
              {Unfold ?
                <View>
                  {
                    Permission.check("ZJZ002") ? <TouchableOpacity style={[styles.claimBox, { marginTop: 20 * scale }]} onPress={() => {
                      this.props.navigation.navigate('BalanceAndFree', {
                        companyName,
                        corpType: type,
                        companyId: this.companyId,
                        tabIndex: 1,
                        corpId: this.pageParams.corpId,
                        isForeign
                      })
                    }}>
                      <Text style={styles.TextNormal}>待认领收款：{isForeign !== 1 ? '￥' : '$'}{this._toMoney(waitClaimAmt)}</Text>
                      <View style={styles.flexRow}>
                        <Text style={styles.TextNormal}>详情</Text>
                        <Image source={require('../../../imgs/arrow-left.png')} style={styles.detailImg} />
                      </View>
                    </TouchableOpacity> : null
                  }
                  {
                    Permission.check("ZJZ002") ?
                      <TouchableOpacity style={[styles.claimBox]} onPress={() => {
                        this.props.navigation.navigate('BalanceAndFree', {
                          companyName,
                          corpType: type,
                          companyId: this.companyId,
                          tabIndex: 2,
                          corpId: this.pageParams.corpId,
                          isForeign
                        })
                      }}>
                        <Text style={styles.TextNormal}>待确认自由款：{isForeign !== 1 ? '￥' : '$'}{this._toMoney(waitConfirmAmt)}</Text>
                        <View style={styles.flexRow}>
                          <Text style={styles.TextNormal}>详情</Text>
                          <Image source={require('../../../imgs/arrow-left.png')} style={styles.detailImg} />
                        </View>
                      </TouchableOpacity>
                      : null
                  }
                  {
                    Permission.check("ZJZ003") ? <TouchableOpacity style={[styles.claimBox]} onPress={() => {
                      this.props.navigation.navigate('BalanceAndFree', {
                        companyName,
                        corpType: type,
                        companyId: this.companyId,
                        tabIndex: 0,
                        corpId: this.pageParams.corpId,
                        isForeign
                      })
                    }}>
                      <Text style={styles.TextNormal}>已认领业务员：{isForeign !== 1 ? '￥' : '$'}{this._toMoney(bizStaffClaimAmt)}</Text>
                      <View style={styles.flexRow}>
                        <Text style={styles.TextNormal}>详情</Text>
                        <Image source={require('../../../imgs/arrow-left.png')} style={styles.detailImg} />
                      </View>
                    </TouchableOpacity> : null
                  }
                </View>
                : null
              }
              {
                (Permission.check("ZJZ002") || Permission.check("ZJZ003")) ? <TouchableOpacity onPress={() => {
                  this.setState({
                    Unfold: !Unfold
                  })
                }} style={{ alignItems: 'center' }}>
                  <Text style={{ fontSize: 10 * scale, color: '#55ADF0', marginBottom: 5 * scale, marginTop: 10 * scale }}>查看认领情况</Text>
                  <Image source={require('../../../imgs/arrow-left.png')} style={Unfold ? styles.claimImg : styles.claimTransImg} />
                </TouchableOpacity> : null
              }
            </View>
            : null
          }
        </View>
        <View style={styles.fixedBox}>
          <View style={styles.flexRow}>
            <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => { this._toggle(true) }}>
              <Text style={styles.statusItemText}>{typeData.length > 0 ? typeData[typesIndex].dictName : '所有类型'}</Text>
              <Image style={styles.imgStyle} source={uriImg} />
            </TouchableOpacity>
            <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }}
              onPress={this._timeOpen}
            >
              <Text style={styles.statusItemText}>{this.dateObj.beginTime || ''}</Text>
              <Text style={[styles.statusItemText, styles.statusItemTextActive]}>至</Text>
              <Text style={styles.statusItemText}>{this.dateObj.endTime || ''}</Text>
              <Image style={styles.imgStyle} source={uriImg} />
            </TouchableOpacity>
          </View>
          <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 * scale }}>
            <Text style={styles.fixedText}>支出 {isForeign !== 1 ? '￥' : '$'}  {this._toMoney(Math.abs(totalInCome))}</Text>
            <Text style={styles.fixedText}>收入 {isForeign !== 1 ? '￥' : '$'}  {this._toMoney(totalExpend)}</Text>
          </View>
        </View>
        {this._renderListItem()}
        <View style={{ marginTop: 20 * scale }}>
          <PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />
        </View>
        <Common type="modal" demoData={(
          <Common type="listRadio" selectIndex={typesIndex} title={'选择资金类型'} listData={typeData} selectCallBack={this._stateCallBack} />
        )} isVisible={isModal} closeCallballFn={() => { this._toggle(false) }} />
        <SlideSelect alertShow={alertShow} options={options} companyIndex={companyIndex}
          select={(val) => {
            this.setState({ choice: val || options[0], alertShow: false, companyIndex: val.selectIndex }, () => {
              this.props.navigation.setParams({
                choice: val || options[0]
              });
              this._refresh();
            })
          }}
          unselect={() => {
            this.setState({ alertShow: false })
          }} />
        {
          showTimeModal ? <RangTime isClear={true} isVisible={true} markedDates={null} startTime={this.dateObj.beginTime} endTime={this.dateObj.endTime} closeCall={() => { this.setState({ showTimeModal: false }) }} resultCall={this._resultCall} /> : null
        }
      </ScrollView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  searchBox: {
    width: 330 * scale
  },
  headBox: {
    // height: 75 * scale,
    paddingVertical: 20 * scale,
    backgroundColor: style.color.themeColor,
    paddingHorizontal: 15 * scale
  },
  imgStyle: {
    width: 12 * scale,
    height: 12 * scale,
    tintColor: '#000',
    marginLeft: 11 * scale,
    // marginTop:2*scale,
    transform: [{ 'rotate': '90deg' }]
  },
  secureEntry: {
    width: 16 * scale,
    height: 16 * scale,
    tintColor: '#79BFFF'
  },
  secureEntryBox: {
    padding: 10 * scale
  },
  flexRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  topText: {
    fontSize: 14 * scale,
    color: '#79BFFF'
  },
  onClickText: {
    fontSize: 14 * scale,
    color: '#FFFFFF'
  },
  onClick: {
    paddingBottom: 5 * scale,
    borderBottomColor: '#fff',
    borderBottomWidth: 2
  },
  unClick: {
    paddingBottom: 5 * scale,
    borderBottomColor: 'transparent',
    borderBottomWidth: 2
  },
  topNum: {
    fontSize: 30 * scale,
    color: '#FFFFFF',
    marginBottom: 35 * scale
  },
  MiddleNum: {
    fontSize: 16 * scale,
    color: '#FFFFFF',
    flex: 1
  },
  detailText: {
    // marginLeft:5*scale,
    fontSize: 12 * scale,
    color: '#FFFFFF',
    fontWeight: '600',
  },
  middleLine: {
    fontSize: 14 * scale,
    color: '#fff',
    // opacity:0.4,
    marginRight: 10 * scale,
    marginLeft: 10 * scale,
  },
  middleBox: {
    padding: 15 * scale,
    backgroundColor: "#fff"
  },
  fixedBox: {
    padding: 15 * scale,
    backgroundColor: style.color.bgGray,
  },
  claimBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 10 * scale
  },
  detailImg: {
    width: 6 * scale,
    height: 9 * scale,
    tintColor: '#000',
    marginLeft: 5 * scale
  },
  claimImg: {
    width: 6 * scale,
    height: 9 * scale,
    tintColor: '#55ADF0',
    transform: [{ 'rotate': '270deg' }]
  },
  claimTransImg: {
    width: 6 * scale,
    height: 9 * scale,
    tintColor: '#55ADF0',
    transform: [{ 'rotate': '90deg' }]
  },
  statusItemText: {
    fontSize: 12 * scale,
    color: '#000'
  },
  TextNormal: {
    fontSize: 14 * scale,
    color: '#000'
  },
  statusItemTextActive: {
    paddingLeft: 3 * scale,
    paddingRight: 3 * scale
  },
  fixedText: {
    fontSize: 12 * scale,
    color: '#657AB0',
    marginRight: 30 * scale
  },
  listItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 69 * scale,
    borderBottomColor: '#E7E7E7',
    borderBottomWidth: 1 * scale,

  },
  listItemTime: {
    fontSize: 10 * scale,
    color: '#000',
    opacity: 0.5,
  },
  listItemNum: {
    fontSize: 15 * scale,
    fontWeight: '600'
  },
})